package cs9322.assign3.resources;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import cs9322.assign3.dao.OrderDao;
import cs9322.assign3.dao.OrdersDao;
import cs9322.assign3.model.Order;

//will map xxx.xxx.xxx/starbucks/orders
@Path("/orders")
public class OrdersResources {
	@Context
	UriInfo uriInfo;
	@Context
	Request request;
	

	
	@GET
	@Produces(MediaType.TEXT_XML)
	public List<Order> getOrderBrowser() {
		List<Order> ol = new ArrayList<Order>();
//		ol.addAll( OrdersDao.instance.getStore().values());
		OrderDao od = new OrderDao();
		ol = od.getAllOrders();
		return ol;
	}
	
	@POST
	@Produces(MediaType.TEXT_XML)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public Order newOrder(
			@FormParam("type") String type,
			@FormParam("size") String size,
			@FormParam("paid") boolean paid,
			@FormParam("addition") String addition,
			@Context HttpServletResponse servletResponse
	) throws IOException {
		Order o = new Order(type, size, paid, addition);
		double price = priceCalculator(type, size);
		o.setPrice(price);
//		OrdersDao.instance.getStore().put(Integer.toString(id), o);
		OrderDao od = new OrderDao();
		o.setStatus("waiting");
		int id = od.add(o);
		URI uri = uriInfo.getAbsolutePathBuilder().path(Integer.toString(id)).build();
		o.setUrl(uri.toString());
		o.setId(id);
		Response.created(uri).build();
		
		od.update(o);
		
		return o;
//		 Redirect to some HTML page 
//		servletResponse.sendRedirect("http://localhost:8080/cs9322.assign3.coffee.client/index.jsp");
	}
	
	
	@Path("{order}")
	public OrderResource getOrder(
			@PathParam("order")  int id) {
		return new OrderResource(uriInfo, request, id);
	}
	
	private double priceCalculator(String type, String size){
		if(type.equals("mocha")){
			if(size.equals("large")){
				return 3.30;
			}else if(size.equals("medium")){
				return 3.60;
			}else if(size.equals("large")){
				return 4.20;
			}
			}
		else if(type.equals("black long")){
			if(size.equals("large")){
				return 3.20;
			}else if(size.equals("medium")){
				return 3.50;
			}else if(size.equals("large")){
				return 4.00;
		}}
		else if(type.equals("Cappuccino")){
			if(size.equals("large")){
				return 3.10;
			}else if(size.equals("medium")){
				return 3.60;
			}else if(size.equals("large")){
				return 4.10;
			}
		}
		return 0;
	}
}
		
	
			

